package com.lantosec.hmrp.core.mvc;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lantosec.hmrp.core.shiro.TokenUtil;
import com.lantosec.hmrp.core.util.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ValidationException;
import java.util.Collection;
import java.util.List;

/**
 * @author 杨成宇
 * @version 1.0
 */
public abstract class BaseController {
    protected <V extends BaseVO<E>, E extends BaseEntity> E VO2Entity(V vo) {
        return BeanUtils.VO2Entity(vo);
    }

    protected <V extends BaseVO<E>, E extends BaseEntity> List<E> VO2Entity(Collection<V> voList) {
        return BeanUtils.VO2Entity(voList);
    }

    protected <V extends BaseVO, E extends BaseEntity<V>> V entity2VO(E entity) {
        return BeanUtils.entity2VO(entity);
    }

    protected <V extends BaseVO, E extends BaseEntity<V>> List<V> entity2VO(Collection<E> entityList) {
        return BeanUtils.entity2VO(entityList);
    }

    protected <V extends BaseVO, E extends BaseEntity<V>> Page<V> entity2VO(IPage<E> page) {
        return BeanUtils.entity2VO(page);
    }

    protected void validationHandler(BindingResult result) {
        if (result.hasFieldErrors()) {
            StringBuilder sb = new StringBuilder();
            sb.append("数据格式不正确:");
            for (FieldError error : result.getFieldErrors()) {
                sb.append("【");
                sb.append(error.getField());
                sb.append("不能为");
                sb.append(error.getRejectedValue());
                sb.append("】");
            }
            throw new ValidationException(sb.toString());
        }
    }
    protected String getUserName(){
        return TokenUtil.getUserName();
    }

    protected String getUserId(){
        return TokenUtil.getUserId();
    }

    protected String getName(){
        return TokenUtil.getName();
    }

    protected String getDeptId(){
        return TokenUtil.getDeptId();
    }

    private String getToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        if(StringUtils.isNotEmpty(token)){
            return token;
        }else{
            return null;
        }
    }
}
